package net.contrend.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBUtils {
    
    /**
     * 
     * @param jndi
     * @return DataSource or null
     * @throws NamingException
     */
    public static DataSource getDataSource(String jndi) throws NamingException {
        DataSource dataSource = null;
        try {
            Context ctx = new InitialContext();
            
            // relative to standard JNDI root for J2EE app
            Context envCtx = (Context) ctx.lookup("java:comp/env");
            dataSource = (DataSource) envCtx.lookup(jndi);
        } catch (NamingException e) {
            e.printStackTrace();
            throw e;
        }
        return dataSource;
    }
    
    /**
     * 
     * @param jndi
     * @return Connection or null
     * @throws NamingException
     * @throws SQLException
     */
    public static Connection getConnction(String jndi) throws NamingException, SQLException {
        Connection connection = null;
        try {
            DataSource dataSource = getDataSource(jndi);
            if (null != dataSource) {
                connection = dataSource.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        } catch (NamingException e) {
            e.printStackTrace();
            throw e;
        }
        return connection;
    }
}
